const { resolve } = require('path')
const isLive = process.env.NODE_ENV === 'production'
const isStag = process.env.NODE_ENV === 'development'

const cdnMirror = {
  ele: '//npm.elemecdn.com',
  zhihu: '//unpkg.zhimg.com',
  unpkg: '//unpkg.com'
}

const cdnHost = cdnMirror.unpkg

module.exports = {
  publicPath: '/',
  chainWebpack: config => {
    const externals = {
      vue: 'Vue',
      axios: 'axios',
      'element-ui': 'ELEMENT',
      'vue-router': 'VueRouter',
      vuex: 'Vuex'
    }
    isLive && config.externals(externals)
    const cdn = {
      css: [`${cdnHost}/element-ui/lib/theme-chalk/index.css`],
      js: [
        `${cdnHost}/vue/dist/vue.min.js`,
        `${cdnHost}/vue-router/dist/vue-router.min.js`,
        `${cdnHost}/vuex/dist/vuex.min.js`,
        `${cdnHost}/axios/dist/axios.min.js`,
        `${cdnHost}/element-ui/lib/index.js`
      ]
    }
    config.plugin('html').tap(args => {
      args[0].cdn = cdn
      return args
    })
    // 这里是对环境的配置，不同环境对应不同的BASE_URL，以便axios的请求地址不同
    config.plugin('define').tap(args => {
      args[0]['process.env'].BASE_URL = JSON.stringify(process.env.BASE_URL)
      return args
    })

    const ofs = ['vue-modules', 'vue', 'normal-modules', 'normal']
    const cssRules = config.module.rule('css')
    const postRules = config.module.rule('postcss')
    const sassRules = config.module.rule('sass')
    const scssRules = config.module.rule('scss')

    const addSassResourcesLoader = (rules, type) => {
      rules
        .oneOf(type)
        .use('sass-resoureces-loader')
        .loader('sass-resources-loader')
        .options({
          resources: resolve(__dirname, './src/style/global/index.scss')
        })
    }
    ofs.forEach(type => {
      addSassResourcesLoader(cssRules, type)
      addSassResourcesLoader(postRules, type)
      addSassResourcesLoader(sassRules, type)
      addSassResourcesLoader(scssRules, type)
    })
    return config
  }
}
